#include <QtCore/QFileInfo>
#include <QtCore/QTextCodec>
#include <QtCore/QTextStream>
#include "unixdaemon/unixdaemon.h"
#include "global.h"

void displayHelpText(const QString &text) {
  qFatal("%s", qPrintable(text));
}

void printHelp(const char *aname) {
  QString help;
  QTextStream str(&help);
  str << "Usage: " << aname << HELP;
  displayHelpText(help);
}

void printVersion() {
  QString version;
  QTextStream str(&version);
  str << '\n' << APP_NAME << ' ' << APP_VERSION
      << " based on Qt " << qVersion() << "\n\n";
  displayHelpText(version);
}

void parseArguments(int argc, char **argv, QString &config_file_path) {
  switch(argc) {
    case 1:
      break;
    case 2:
      if(strcmp(argv[1], HELP_OPTION1) == 0 ||
         strcmp(argv[1], HELP_OPTION2) == 0) {
        printHelp(argv[0]);
      } else if(strcmp(argv[1], VERSION_OPTION1) == 0 ||
                strcmp(argv[1], VERSION_OPTION2) == 0) {
        printVersion();
      } else {
        printHelp(argv[0]);
      }
      break;
    case 3:
      if(strcmp(argv[1], CONFIG_OPTION) == 0) {
        QFileInfo config_file(argv[2]);
        if(config_file.exists()) {
          config_file_path = config_file.absoluteFilePath();
        } else {
          displayHelpText(QString("Config file %1 not exist")
                            .arg(config_file.absoluteFilePath()));
        }
      } else {
        printHelp(argv[0]);
      }
      break;
    default:
      printHelp(argv[0]);
      break;
  }
}

int main(int argc, char **argv) {
  QString config_file(DEFAULT_CONFIG_PATH);

  parseArguments(argc, argv, config_file);

  QCoreApplication app(argc, argv);

  QTextCodec *codec = QTextCodec::codecForName("UTF-8");
  QTextCodec::setCodecForTr(codec);
  QTextCodec::setCodecForCStrings(codec);
  QTextCodec::setCodecForLocale(codec);

  smsbilling::UnixDaemon a(config_file);

  a.daemonize();

  return app.exec();
}
